<template>
  <div>
    <div class="gameEntry_shadow check_shadow">
      <div v-if="userInfo" class="individual_check gl_clear">
        <div class="individual_check_wrap gl_fl">
          <span class="gl_mr_10">{{ userInfo.name }}</span>
          <span>{{ dictGenderMap[userInfo.genderCode] ? dictGenderMap[userInfo.genderCode].value : '' }} </span>
          <span>
            {{ userInfo.birthDate ? userInfo.birthDate.slice(0, 10) : '' }}
          </span>
        </div>
        <el-button :loading="checkEntryBtnLoading" class="checkEntry_btn gl_fl" type="primary" @click="getEntryAndSubstationList">点击检测，获取项目</el-button>
      </div>
    </div>

    <div v-if="entryList.length" class="gameEntry_shadow entry_shadow">
      <!-- 联赛且为决赛时，需要显示赛区选择 -->
      <div v-if="gameInfo.isFinal && substationList.length" class="event_group">
        <div class="event_title">赛区选择</div>
        <div class="event_list">
          <el-radio-group v-model="activeSubstation">
            <el-radio
              v-for="(item, index) in substationList"
              :key="index"
              style="margin-left: 0px"
              class="event_item"
              :label="item.id"
              border
            >
              {{ item.competitionName }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <div v-for="(item, index) in entryShowData" :key="index" class="event_group">
        <div class="event_title">{{ item.name }}</div>
        <div>
          <el-checkbox-group v-model="entryCheckGroupData[item.categoryId]" :max="item.maxEntry">
            <el-checkbox v-for="(jtem, jndex) in item.children" :key="jndex" class="event_item" :label="jtem.id" border :disabled="Boolean(isCategory && isAOrB && jtem.categoryGroupTypeCode != 'C' && isAOrB != jtem.categoryGroupTypeCode)">
              <span>{{ jtem.eventGroupName }}{{ jtem.eventShortName }}</span>
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
    </div>
    <!-- <div v-else class="individual_list_noData">
      <p>请检测并获取项目</p>
    </div> -->

    <el-row v-show="entryList.length" class="control_row">
      <el-col :span="24" align="center">
        <el-button type="primary" size="small" :loading="submitLoading" @click="clickSubmit()">提交报名</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  api_POST_EventsManagementEntryQueryEventsToEntryForRegisters, // 1-获取已存在人员可报的赛事项目列表
  api_POST_EventsManagementEntryQuerySubCompetitionsToEntryForRegisters // 0-获取已存在人员联赛决赛代表的分站赛赛事列表
} from '@/extend/api/gameswaggerApi/app';

import {
  SiSTKWEventsManagementGetEntryEventsInput // 1-获取已存在人员可报的赛事项目列表
} from '@/lib/form/game/swaggerForm';

export default {
  props: {
    submitLoading: {
      type: Boolean,
      default: false
    },
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    dict: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      activeSubstation: '',
      substationList: [],
      entryVO: new SiSTKWEventsManagementGetEntryEventsInput(), // 1-获取已存在人员可报的赛事项目列表
      entryList: [], // 原始的报项列表
      entryShowData: {}, // 处理后用于页面显示的报项数据
      entryCheckGroupData: {}, // 根据报项数据复选框数据
      isCategory: false,
      isAOrB: '',
      categoryObj: {},
      checkEntryBtnLoading: false
    };
  },
  computed: {
    dictGenderMap() {
      const _map = {};
      this.dict.gender.forEach(item => {
        _map[item.code] = item;
      });
      return _map;
    }
  },
  watch: {
    entryCheckGroupData: {
      deep: true,
      handler(newVal) {
        let ab = '';
        for (const k in newVal) {
          const ktem = newVal[k];
          if (ktem.length > 0 && this.categoryObj[k] !== 'C' && this.categoryObj[k] !== null) {
            ab = this.categoryObj[k] || '';
          }
        }
        const code = this.gameInfo.setting && this.gameInfo.setting.chargeTypeCode;
        this.isCategory = code === 'Category';
        this.isAOrB = ab;
        console.log(newVal, this.isAOrB);
      }
    }
  },
  methods: {
    getEntryAndSubstationList () {
      if (this.gameInfo.isFinal) {
        this.getSubstationList({
          competitionId: this.gameInfo.id,
          registerId: this.requiredIdData.registerId,
          hasEntriedEvent: true
        });
      }
      this.checkEntry();
    },
    // 获取已存在人员联赛决赛代表的分站赛赛事列表
    getSubstationList (vo) {
      api_POST_EventsManagementEntryQuerySubCompetitionsToEntryForRegisters(vo)
        .then(
          res => {
            this.substationList = res || [];
            const _findResult = res.find(item => item.hasUsed);
            this.activeSubstation = _findResult ? _findResult.id : '';
          }
        )
        .catch(
          error => {
            this.$message({
              message: `获取分站列表失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 检测报项信息
    checkEntry () {
      if (this.userInfo.id) {
        this.checkEntryBtnLoading = true;
        this.entryVO.competitionId = this.gameInfo.id;
        this.entryVO.registerId = this.requiredIdData.registerId;
        this.entryVO.delegationId = null; // 个人报名不需要 delegationId
        this.entryVO.hasEntriedEvent = true;
        api_POST_EventsManagementEntryQueryEventsToEntryForRegisters(this.entryVO)
          .then(
            res => {
              this.checkEntryBtnLoading = false;
              if (res.length) {
                this.entryList = res;
                this.entryCheckGroupData = {};
                this.entryShowData = this.formatEntryShowData(res);
              } else {
                this.$message({
                  message: `没有检测到可以报名的项目`,
                  type: 'warning',
                  showClose: true
                });
              }
            }
          )
          .catch(
            error => {
              this.checkEntryBtnLoading = false;
              this.$message({
                message: `获取人员可报的赛事项目列表失败 ${error.error.message}`,
                type: 'error',
                showClose: true
              });
            }
          );
      }
    },
    // 处理报项显示数据
    formatEntryShowData (list) {
      const _returnData = {};
      const category = {};
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        item.$categoryId = item.eventCategoryId;
        if (!category[item.$categoryId]) {
          category[item.$categoryId] = item.categoryGroupTypeCode;
        }
        if (_returnData[item.$categoryId]) {
          _returnData[item.$categoryId].children.push(item);
        } else {
          _returnData[item.$categoryId] = {
            categoryId: item.$categoryId,
            categoryCreateTime: item.eventCategoryCreationTime,
            name: item.eventCategoryName,
            maxEntry: item.categoryMaxEntry,
            children: [item]
          };
          // 处理复选框数据
          this.formatEntryShowDataCheckbox(item.$categoryId);
        }
        // 报了这个项目
        if (item.athleteHasEntried) {
          this.entryCheckGroupData[item.$categoryId].push(item.id);
        }
      }
      this.categoryObj = category;
      for (const k in _returnData) {
        const ktem = _returnData[k];
        let hasEntry = 0;
        ktem.children.forEach(item => {
          if (item.athleteHasEntried) {
            hasEntry++;
          }
        });
        ktem.hasEntry = hasEntry;
        ktem.children.sort((a, b) => {
          const _a = a.eventCreationTime;
          const _b = b.eventCreationTime;
          if (_a < _b) { return -1; }
          if (_a > _b) { return 1; }
          return 0;
        });
      }

      const _returnList = Object.values(_returnData);
      _returnList.sort((a, b) => {
        const _a = a.categoryCreateTime;
        const _b = b.categoryCreateTime;
        if (_a < _b) { return -1; }
        if (_a > _b) { return 1; }
        return 0;
      });
      return _returnList;
    },
    // 处理报项显示数据的复选框
    formatEntryShowDataCheckbox (categoryId) {
      if (categoryId in this.entryCheckGroupData) {
        return;
      }
      this.$set(this.entryCheckGroupData, categoryId, []);
    },
    // 点击提交报名
    clickSubmit () {
      let _eventIds = [];
      for (const k in this.entryCheckGroupData) {
        const ktem = this.entryCheckGroupData[k];
        _eventIds = _eventIds.concat(ktem);
      }
      // emit
      if (_eventIds.length) {
        this.$emit(
          'onSubmitIndividualEntry',
          {
            competitionId: this.entryVO.competitionId,
            eventIds: _eventIds,
            delegationId: this.requiredIdData.delegationId,
            registerId: this.entryVO.registerId,
            entrySubstationId: this.activeSubstation
          },
          this.entryList
        );
      } else {
        this.$message({
          message: `请选择要报名的项目`,
          type: 'warning',
          showClose: true
        });
      }
    },
    // 点击执行上一步操作
    clickPrevStep () {
      this.$emit('onPrevStep');
    },
    onRemovedAthleteForCheckEntry () {
      this.getEntryAndSubstationList();
    }
  }
};
</script>

<style>
.individual_check .el-button {
  border-radius: 0 4px 4px 0;
}
.el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0px;
}
</style>

<style lang="scss" scoped>
.check_shadow {
  padding: 20px 30px;
  margin-bottom: 10px;
}
.entry_shadow {
  padding: 20px 30px;
  background-color: #fff;
}
.individual_check_wrap {
  box-sizing: border-box;
  width: calc(100% - 180px);
  height: 40px;
  border: 1px solid #C0C4CC;
  border-right: none;
  border-radius: 8px 0 0 8px;
  text-align: center;
  line-height: 38px;
  color: #353434;
}
.event_group {
  margin-bottom: 10px;
}
.control_row {
  margin-bottom: 30px;
}
.event_title {
  position: relative;
  height: 22px;
  line-height: 22px;
  font-size: 16px;
  font-weight: bold;
  color: #353434;
  margin-bottom: 8px;
}
.event_item {
  margin-bottom: 10px;
  margin-right: 10px;
}
.individual_list_noData {
  padding: 140px 0px 215px;
  text-align: center;
  font-size: 16px;
  color: #c1c1c1;
}
.checkEntry_btn {
  width: 180px;
}
</style>
